package com.easy.core.util;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 描述：cookie工具类
 * @package com.easy.core.util
 * @class CookieUtils
 */
public class CookieUtil {

	/**
	 * 设置cookie
	 * @param response
	 * @param name		cookie名字
	 * @param value		cookie值
	 * @param maxAge	cookie生命周期，以秒为单位。如果设置为负值的话，则为浏览器进程Cookie(内存中保存)，关闭浏览器就失效
	 * @param path		设置路径，这个路径即该工程下都可以访问该cookie 如果不设置路径，那么只有设置该cookie路径及其子路径可以访问
	 */
	public static void addCookie(HttpServletResponse response, String name, String value, int maxAge, String path) {
		Cookie cookie = new Cookie(name, value);
		if(null != path) { cookie.setPath(path); }
		if(0 < maxAge) { cookie.setMaxAge(maxAge); }
		response.addCookie(cookie);
	}
	

	/**
	 * 根据名字获取cookie
	 * @param request
	 * @param name cookie名字
	 * @return
	 */
	public static Cookie getCookieByName(HttpServletRequest request,String name){
		Map<String,Cookie> cookieMap = readCookieMap(request);
		if(cookieMap.containsKey(name)){
			Cookie cookie = (Cookie)cookieMap.get(name);
			return cookie;
		}else{
			return null;
		}
	}
	
	/**
	 * 将cookie封装到Map里面
	 * @param request
	 * @return
	 */
	private static Map<String,Cookie> readCookieMap(HttpServletRequest request){	
		Map<String,Cookie> cookieMap = new HashMap<String,Cookie>();
		Cookie[] cookies = request.getCookies();
		if(null!=cookies){
			for(Cookie cookie : cookies){
				cookieMap.put(cookie.getName(), cookie);
			}
		}
		return cookieMap;
	}
	
}
